﻿#include"LoginController.h"
#include"XQAlgorithm.h"
#include"XQDatabaseConnectionView.h"
#include"XQSettingsInfo.h"
#include"XQDatabaseObject.hpp"
#include"XQFuncEventFilter.hpp"
#include"XQFuncEvent.h"
#include"XQGraphicsViewWidget.h"
#include<QDebug>
#include<QMessageBox>
LoginController::LoginController(QObject* parent)
	:StashManageControllerObject(parent)
{
	init();
}

LoginController::~LoginController()
{

}

LoginView* LoginController::loginView() const
{
	return m_LoginView;
}

void LoginController::copyModel(StashManageModelObject* model)
{
	if (model == nullptr)
		return;
	if(this->model()->mysql()!=nullptr)
		QObject::disconnect(this->model()->mysql(), &XQMySql::connectedSignals, this, &LoginController::initDatabaseTable);
	StashManageControllerObject::copyModel(model);
	QObject::connect(model->mysql(),&XQMySql::connectedSignals,this,&LoginController::initDatabaseTable, Qt::DirectConnection);
}


void LoginController::showView()
{
	if (ISNULL(m_LoginView, "视图指针NULL"))
		return;
	m_LoginView->show();
}

void LoginController::loginSlots(const QString& account, const QString& password)
{
	if (account.isEmpty() || password.isEmpty())
	{
		QMessageBox::information(m_LoginView, "登录", "登录失败,用户名或密码错误不能为空");
		return;
	}
	model()->addMySqlThreadTask([=] {
		auto mysql = model()->mysql()/*->cloneDatabase_ScopedPointer()*/;
		//判断是否连接了数据库
		if (!mysql->isOpen())
		{
			new XQFuncEvent(this, [this]
				{
				QMessageBox::information(m_LoginView, "数据库", "还未连接上数据库");
			m_LoginView->Database(); 
				});
			return;
		}
		auto user=model<LoginModel>()->loginUserMySql(account,password);
		if (user.uuid().isEmpty())
		{
			new XQFuncEvent(this, [this]
				{
			QMessageBox::information(m_LoginView, "登录", "登录失败,用户名或密码错误");
				});
			return;
		}
		new XQFuncEvent(this, [=]
			{
				m_LoginView->addCurrentUser();
				model<LoginModel>()->saveLoginCurrentAccountSettings(user.account());
				model<LoginModel>()->saveLoginAccounts(m_LoginView->users());
				model()->setUserData(user);
				emit loginSignals(user);
				//m_LoginView->close();

				
			});
		});
	

}

void LoginController::loginViewUserNameChangedSlots(const QString& account)
{
	static QDateTime time= QDateTime::currentDateTime();
	if (time.addSecs(1) < QDateTime::currentDateTime())
	{
		time= QDateTime::currentDateTime();
		//qDebug() << "输入的账号改变了" << account;
		model()->addMySqlThreadTask([=] {
			auto portrait=model<LoginModel>()->userePortraitMySql(account);
			//if (!portrait.isNull())
			{
				new XQFuncEvent(this, [=] {
					m_LoginView->setPortrait(portrait); 
					});
			}
			
			});
	}
	
}

void LoginController::createDatabaseConnectionViewSlots(XQDatabaseConnectionView* view)
{
	auto database = model<LoginModel>()->databaseConnectionSettings();
	view->setModel(database);

	//保存创建的视图指针
	m_databaseConnectionView = view;
	/*connect(view, &QWidget::destroyed, [this] {m_databaseConnectionView = nullptr; });*/
}

void LoginController::databaseConnectionSlots(XQDatabaseConnectionModel data)
{
}

void LoginController::databaseSaveSlots(XQDatabaseConnectionModel data)
{
	//验证是否通过
	if (XQDatabaseObject::connectionVerify(data))
	{
		QMessageBox::information(nullptr, "保存", "已将连接信息保存到本地");
		model()->addMySqlThreadTask([=] {model()->connectionMySql(data); });
	}
	else
	{
		auto ret=QMessageBox::information(nullptr, "保存", "连接失败确定要保存吗", QMessageBox::Save| QMessageBox::No, QMessageBox::No);
		if (ret & QMessageBox::No)
			return;
	}
	//保存配置文件
	model<LoginModel>()->saveDatabaseConnectionSettings(data);
	if (m_databaseConnectionView)
		m_databaseConnectionView->close();
}

void LoginController::createAccountViewSlots(XQCreateUserView* view)
{
	if (view == nullptr)
		return;
	m_createAccount = view;

}

void LoginController::registerAccountSlots(const XQUserData& user)
{
	//
	if(m_updateVerify.addSecs(5*60)<QDateTime::currentDateTime())
	{
		QMessageBox::information(m_createAccount,"注册","验证码已经失效了，请重新获取");
		return;
	}
	if (m_verify != m_createAccount->verify())
	{
		QMessageBox::information(m_createAccount, "注册", "验证码错误，请重新输入");
		return;
	}
	model()->addMySqlThreadTask([=] {
		bool ok = model<LoginModel>()->registerAccountMySql(user);
		new XQFuncEvent(this, [=] {
			if (ok)
			{
				QMessageBox::information(m_createAccount, "注册", "注册账号成功");
				m_createAccount->close();
			}
			else
			{
				QMessageBox::information(m_createAccount, "注册", "注册账号失败");
			}
			});
		});
	
	//qDebug() << "注册按钮";
}

void LoginController::sendVerifySlots()
{
	auto email = m_createAccount->email();
	auto verify = random(100000, 999999);
	if (model()->sendVerifyMail(email, "注册", verify))
	{
		m_verify = verify;
		m_updateVerify = QDateTime::currentDateTime();
	}
}


void LoginController::init()
{
	installEventFilter(new XQFuncEventFilter(this));
	setModel(new LoginModel);
	//model()
	m_LoginView = new LoginView();
	m_LoginView->setAttribute(Qt::WA_DeleteOnClose);
	m_LoginView->init();
	QObject::connect(m_LoginView, &QWidget::destroyed,this,&QObject::deleteLater);
	QObject::connect(this, &QObject::destroyed, m_LoginView, &QObject::deleteLater);
	QObject::connect(m_LoginView,&LoginView::loginSignals,this, &LoginController::loginSlots);
	QObject::connect(m_LoginView,&LoginView::createDatabaseConnectionViewSignals,this,&LoginController::createDatabaseConnectionViewSlots);
	QObject::connect(m_LoginView, &LoginView::databaseConnectionSignals, this, &LoginController::databaseConnectionSlots);
	QObject::connect(m_LoginView, &LoginView::databaseSaveSignals, this, &LoginController::databaseSaveSlots);

	QObject::connect(m_LoginView, &LoginView::createAccountViewSignals, this, &LoginController::createAccountViewSlots);
	QObject::connect(m_LoginView, &LoginView::registerAccountSignals, this, &LoginController::registerAccountSlots);
	QObject::connect(m_LoginView, &LoginView::sendVerifySignals, this, &LoginController::sendVerifySlots);
	QObject::connect(m_LoginView, &LoginView::userNameChangedSignals, this, &LoginController::loginViewUserNameChangedSlots);
}

void LoginController::initDatabaseTable()
{
	model<LoginModel>()->initDatabaseTable();
}

void LoginController::readLoginSettings()
{
	auto& model = *this->model<LoginModel>();
	auto login = m_LoginView;
	//读取mysql连接信息
	auto connectionData = model.databaseConnectionSettings();
	auto test = model.loginAccountsSettings();
	model.addMySqlThreadTask([=]
		{
			//验证连接是否可用
			if(XQMySql::connectionVerify(connectionData))
			{
				//new XQFuncEvent(this, [=]
					{this->model<LoginModel>()->connectionMySql(connectionData); }
				//);
					//qDebug() << "已经连接上数据库";
			}
			else
			{
				
			}
		});
	//model.connectionMySql(connectionData);
	//读取本地账号
	auto accounts= model.loginAccountsSettings();
	
	for (auto &user:accounts)
	{
		//qDebug() << user.toVariantMap();
		login->addUser(user);
		login->selectUser(user.userName());
		/*auto view = new XQGraphicsViewWidget;
		view->setAttribute(Qt::WA_DeleteOnClose);
		view->setPixmap("猫哥出手，必属精品",user.portrait() );
		view->show();*/
	}
	//读取显示的当前账号
	auto CurrentUser = model.loginCurrentAccountSettings();
	if(!CurrentUser.isEmpty())
	{
		login->selectUser(CurrentUser);
		//login->setCurrentUserName(CurrentUser);
	
	}
}
